package com.frank.code_notes.C01_array;

import cn.hutool.core.lang.Console;

/**
 * @Description LCR 146. 螺旋遍历二维数组
 * @Author zhoujr
 * @Data 2024/11/29 9:33
 */
public class LCR146SpiralArray {

    /**
     * @Description 确认四个边界，逐条边遍历，向内收缩，大于对边结束
     */
    public static int[] spiralArray(int[][] array) {
        if (array == null || array.length == 0 || array[0].length == 0)
            return new int[]{};
        int l = 0, t = 0, r = array[0].length - 1, b = array.length - 1, x = 0;
        int[] res = new int[(r + 1) * (b + 1)];
        while (true) {
            for (int i = l; i <= r; i++) res[x++] = array[t][i]; // left to right
            if (++t > b) break;
            for (int i = t; i <= b; i++) res[x++] = array[i][r]; // top to bottom
            if (l > --r) break;
            for (int i = r; i >= l; i--) res[x++] = array[b][i]; // right to left
            if (t > --b) break;
            for (int i = b; i >= t; i--) res[x++] = array[i][l]; // bottom to top
            if (++l > r) break;
        }
        return res;
    }

    public static void main(String[] args) {
        Console.log(spiralArray(new int[][]{
                {1, 2, 3},
                {4, 5, 6},
                {7, 8, 9}
        }));
    }

}
